package com.visceb.backstage.controller;
import com.visceb.backstage.dao.assRepository;
import com.visceb.backstage.dao.subjectRepository;
import com.visceb.backstage.entity.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.visceb.backstage.entity.Ass;
import java.sql.Timestamp;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ass")
@CrossOrigin()
public class assController {
    @Autowired
    private assRepository assrepository;
    @Autowired
    private subjectRepository subjectrepository;

//    选择对应的课程号的所有评价
    @RequestMapping(value ="/assBysubjcetId", method = RequestMethod.GET)
    @ResponseBody
    public List<Ass> findAss(String subjectId) {
        List<Ass> ass;
        ass = assrepository.findAllBySubjectId(Integer.parseInt(subjectId));
        return ass;
    }

//    用户进行评分,添加新的评价
    @RequestMapping(value ="/addAss", method = RequestMethod.POST)
    @ResponseBody
    public int addAss(@RequestBody Ass ass) {
        Ass assSearch;
        if(ass.getUsername() == null)
            return 2;
        assSearch = assrepository.findByUsernameAndSubjectId(ass.getUsername() , ass.getSubjectId());

        if(assSearch == null) {
//            保存评价
            assrepository.save(ass);
//            更改该课程的信息，如评分总人数，平均分，对应评分的人数
            Subject sub = subjectrepository.findById(ass.getSubjectId());

            sub.setAssNum(sub.getAssNum() + 1);
            System.out.println(sub.getAssNum());

            switch (ass.getStar()){
                case 1: sub.setOneStarNum(sub.getOneStarNum() +1);
                    break;
                case 2: sub.setTwoStarNum(sub.getTwoStarNum() +1);
                    break;
                case 3: sub.setThreeStarNum(sub.getThreeStarNum() +1);
                    break;
                case 4: sub.setFourStarNum(sub.getFourStarNum() +1);
                    break;
                case 5: sub.setFiveStarNum(sub.getFiveStarNum() +1);
                    break;
                    default:break;
            }
            System.out.println(sub.getOneStarNum());
            int total =sub.getOneStarNum() + sub.getTwoStarNum()*2 +sub.getThreeStarNum()*3 + sub.getFourStarNum()*4 +sub.getFiveStarNum()*5;
//            System.out.println(total);
            double ave = (total*1.00)/sub.getAssNum();
//            System.out.println(ave);
            sub.setAveScore(ave);
            subjectrepository.save(sub);
            return 1;
        }else{
            return 0;
        }
    }
}
